package music

import (
	"dustbe/database"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-gonic/gin"
)

type InitStaffPackage struct {
	Total int `json:"total"`
	Staffs []database.StaffNode `json:"staffs"`
}

func InitStaff(c *gin.Context) {
	staffNodes, err := database.GetStaffByPage(1, StaffNumOnePage)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	staffNum, err := database.GetStaffNumber()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "获取staff数量失败"})
		return
	}
	
	initStaffPackage := InitStaffPackage{
		Total: staffNum,
		Staffs: staffNodes,
	}
	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : initStaffPackage})
}

func QueryStaffsByPageId(c *gin.Context) {
	pageId, _ := strconv.Atoi(c.Query("pageId"))
	staffNodes, err := database.GetStaffByPage(pageId, StaffNumOnePage)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : staffNodes})
}

type StaffPackage struct {
	StaffInfo database.StaffNode `json:"staffInfo"`
	AlphaTex ExportAlphaTex `json:"alphaTex"`
}

func GetStaffById(c *gin.Context) {
	staffId, _ := strconv.Atoi(c.Query("staffId"))
	staffNode, err := database.GetStaffById(int64(staffId))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	dustUser, err := database.FindUserByName(staffNode.PublisherName)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}
	publisherId := dustUser.Id
	var exportAlphaTex ExportAlphaTex
	staffPath := fmt.Sprintf("%s/%d-%d.json", staffRoot, publisherId, staffId)

	file, err := os.Open(staffPath)	
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "打开本地json出错"})
		return
	}
	defer file.Close()
	
	data, err := ioutil.ReadAll(file)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "读取本地json出错"})
		return
	}

	err = json.Unmarshal(data, &exportAlphaTex)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "解析本地json出错"})
		return
	}

	staffPackage := StaffPackage{
		StaffInfo: staffNode,
		AlphaTex: exportAlphaTex,
	}

	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : staffPackage})
}